<?php

namespace Trawind\VerifyPermission\FieldPermission;

use Trawind\Helpers\UserHelper;  
use Trawind\Remotes\Repositories\User\RoleFieldPermissionsRepositoryEloquent;
use Illuminate\Database\Eloquent\Model;

class FieldPermission
{
    public function __construct($modelOrbusinessType)
    {
        if ($modelOrbusinessType instanceof Model) 
            $this->businessType = $modelOrbusinessType->businessType;
        else 
            $this->businessType = $modelOrbusinessType;
        $this->field = $this->field();
    }

    public function field():?array
    {
        if ($this->getField() !== false)
            return $this->getField();
        $result = (new RoleFieldPermissionsRepositoryEloquent())->setUrl('role-field-permissions/user-role-field-permission')->result();
        $this->setField($result ?? []);
        return $this->getField();
    }

    public function setField(?array $data): void
    {
        $data = array_map(function ($item) {
            return [
                'field_id' => $item['field_id'],
                'business_type_id' => $item['business_type_id'],
                'name' => $item['name'],
                'range_type_id' => $item['range_type_id'],
            ];  
        }, $data);
        RedisManager()->setex("field_permission:user_id:" . UserHelper::userId(), 3600 * 24 * 7, serialize($data));
    }

    public function getField()
    {
        return unserialize(RedisManager()->get("field_permission:user_id:" . UserHelper::userId()));
    }

    public function retrievedField(): ?array
    {
        $arr = array_filter($this->field, function ($item) {
            if ($item['business_type_id'] == $this->businessType && $item['range_type_id'] == 11)
                return $item;
        });
        return array_column($arr, 'name');
    }

    public function retrievedFieldId(): ?array
    {
        $arr = array_filter($this->field, function ($item) {
            if ($item['business_type_id'] == $this->businessType && $item['range_type_id'] == 11)
                return $item;
        });
        return array_column($arr, 'field_id');
    }

    public function savingField(): ?array
    {
        $arr = array_filter($this->field, function ($item) {
            if ($item['business_type_id'] == $this->businessType)
                return $item;
        });
        return array_column($arr, 'name');
    }
}
